﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using System.Web.Script.Serialization;
using Bot_Schedule.Lib;
using System.Net;
using System.Collections;
using Codeplex.Data;
using DevExpress.XtraGrid.Views.BandedGrid;
using DevExpress.XtraWaitForm;
using DevExpress.XtraScheduler;
using DevExpress.XtraScheduler.Drawing;
using System.Drawing.Drawing2D;
using DevExpress.XtraTreeList.Nodes;


namespace Bot_Schedule
{
    public partial class frm_main : XtraForm
    {
        DataTable dtWebsite;
        DataTable dtChiTieu;
        DataTable dtpageUrl;
        DataTable dtBots;
        DataTable dtSchedules;
        DataTable dtLogs;
        DataTable dtCustomer;
        ProgressPanel wait;
        WebClient wc;
        public frm_main()
        {
            InitializeComponent();
            wc = new WebClient();
            initDB();
            loadwebsite();
            printWebsite();
            loadDTLich();
            loadDTLog();
            loadDTVetinh();
            printVetinh();
            printLog();
            printLich();
            loadCustomer();
        }
        void initDB()
        {
            dtWebsite = new DataTable();
            dtWebsite.Columns.Add("Stt", typeof(string));
            dtWebsite.Columns.Add("wsURL", typeof(string));
            dtWebsite.Columns.Add("isEnable", typeof(string));
            dtWebsite.Columns.Add("customer_id", typeof(string));
            dtpageUrl = new DataTable();
            dtpageUrl.Columns.Add("Stt", typeof(string));
            dtpageUrl.Columns.Add("webID", typeof(string));
            dtpageUrl.Columns.Add("PageUrl", typeof(string));
            dtpageUrl.Columns.Add("isEnable", typeof(string));
            dtpageUrl.Columns.Add("Title", typeof(string));
            dtpageUrl.Columns.Add("Description", typeof(string));
            dtpageUrl.Columns.Add("Keyword", typeof(string));
            dtChiTieu = new DataTable();
            dtChiTieu.Columns.Add("Stt", typeof(string));
            dtChiTieu.Columns.Add("webId", typeof(string));
            dtChiTieu.Columns.Add("batdau", typeof(DateTime));
            dtChiTieu.Columns.Add("ketthuc", typeof(DateTime));
            dtChiTieu.Columns.Add("luotxem", typeof(string));
            dtChiTieu.Columns.Add("trangthai", typeof(string));
            dtBots = new DataTable();
            dtBots.Columns.Add("Stt", typeof(string));
            dtBots.Columns.Add("tenmay", typeof(string));
            dtBots.Columns.Add("trangthai", typeof(string));
            dtBots.Columns.Add("dsWebs", typeof(string));
            dtSchedules = new DataTable();
            dtSchedules.Columns.Add("Stt", typeof(string));
            dtSchedules.Columns.Add("ngay", typeof(DateTime));
            dtSchedules.Columns.Add("chitieuId", typeof(string));
            dtSchedules.Columns.Add("wsUrl", typeof(string));
            dtSchedules.Columns.Add("luotxem", typeof(string));
            dtSchedules.Columns.Add("luocxemhientai", typeof(string));
            dtLogs = new DataTable();
            dtLogs.Columns.Add("Stt", typeof(string));
            dtLogs.Columns.Add("pageID", typeof(string));
            dtLogs.Columns.Add("PageUrl", typeof(string));
            dtLogs.Columns.Add("ipAddress", typeof(string));
            dtLogs.Columns.Add("vetinhid", typeof(string));
            dtLogs.Columns.Add("batdau", typeof(DateTime));
            dtLogs.Columns.Add("ketthuc", typeof(DateTime));
            dtLogs.Columns.Add("luotxem", typeof(string));
            dtLogs.Columns.Add("WebsiteID", typeof(string));
            dtLogs.Columns.Add("tenmay", typeof(string));
            dtCustomer = new DataTable();
            dtCustomer.Columns.Add("Stt", typeof(string));
            dtCustomer.Columns.Add("Fullname", typeof(string));
            dtCustomer.Columns.Add("Email", typeof(string));
        }
        void loadCustomer(string value = "")
        {
            var result = Functions.convertData(wc, "customers", Functions.EncodeTo64(value));
            foreach (var item in result.customers)
            {
                DataRow dr = dtCustomer.NewRow();
                dr["Stt"] = item.Stt;
                dr["Fullname"] = item.Fullname;
                dr["Email"] = item.Email;
                dtCustomer.Rows.Add(dr);
            }
        }
        void loadwebsite(string value = "")
        {
            dtWebsite.Rows.Clear();
            dtChiTieu.Rows.Clear();
            dtpageUrl.Rows.Clear();
            var result = Functions.convertData(wc, "websites", Functions.EncodeTo64(value));
            foreach (var item in result.website)
            {
                DataRow dr = dtWebsite.NewRow();
                dr["Stt"] = item.Stt;
                dr["wsURL"] = item.wsURL;
                dr["isEnable"] = item.isEnable;
                dr["customer_id"] = item.customer_id;
                dtWebsite.Rows.Add(dr);
                //
                foreach (var ct in item.lichtrinh)
                {
                    DataRow drct = dtChiTieu.NewRow();
                    drct["Stt"] = ct.Stt;
                    drct["webId"] = ct.webId;
                    drct["batdau"] = ct.batdau;
                    drct["ketthuc"] = ct.ketthuc;
                    drct["luotxem"] = ct.luotxem;
                    drct["trangthai"] = ct.trangthai;
                    dtChiTieu.Rows.Add(drct);
                }
                foreach (var ct in item.pages)
                {
                    DataRow drpg = dtpageUrl.NewRow();
                    drpg["Stt"] = ct.Stt;
                    drpg["webID"] = ct.WebsiteID;
                    drpg["PageUrl"] = ct.PageUrl;
                    drpg["isEnable"] = ct.isEnable;
                    drpg["Title"] = ct.Title;
                    drpg["Description"] = ct.Description;
                    drpg["Keyword"] = ct.Keyword;
                    dtpageUrl.Rows.Add(drpg);
                }
            }
        }

        void loadDTLich(string value = "")
        {
            dtSchedules.Rows.Clear();
            var result = Functions.convertData(wc, "schedules", value);
            foreach (var item in result.lich)
            {
                DataRow dr = dtSchedules.NewRow();
                dr["Stt"] = item.Stt;
                dr["ngay"] = item.ngay;
                dr["chitieuId"] = item.chitieuId;
                dr["wsUrl"] = item.wsUrl;
                dr["luotxem"] = item.luotxem;
                dr["luocxemhientai"] = item.luocxemhientai;
                dtSchedules.Rows.Add(dr);
            }
        }
        void loadDTVetinh(string value = "")
        {
            dtBots.Rows.Clear();
            var result = Functions.convertData(wc, "bots", value);
            if (result == null) return;
            foreach (var item in result.bots)
            {
                DataRow dr = dtBots.NewRow();
                dr["Stt"] = item.Stt;
                dr["tenmay"] = item.tenmay;
                dr["trangthai"] = item.trangthai;
                dr["dsWebs"] = item.dsWebs;
                dtBots.Rows.Add(dr);
            }
        }
        void loadDTLog(string value = "")
        {
            dtLogs.Rows.Clear();
            var result = Functions.convertData(wc, "logs", value);
            if (result == null) return;
            foreach (var item in result.pagelogs)
            {
                DataRow dr = dtLogs.NewRow();
                dr["Stt"] = item.Stt;
                dr["pageID"] = item.pageID;
                dr["PageUrl"] = item.PageUrl;
                dr["ipAddress"] = item.ipAddress;
                dr["vetinhid"] = item.vetinhid;
                dr["batdau"] = item.batdau == null ? DateTime.Now : item.batdau;
                try { dr["ketthuc"] = item.ketthuc; }
                catch { dr["ketthuc"] = DateTime.Now; }
                dr["luotxem"] = item.luotxem;
                dr["WebsiteID"] = item.WebsiteID;
                dr["tenmay"] = item.tenmay;
                dtLogs.Rows.Add(dr);
            }
        }
        //print
        void printWebsite(string value = "")
        {
            listWeb.Items.Clear();
            treeList1.Nodes.Clear();
            DataRow[] rows = dtWebsite.Select(value);
            foreach (DataRow row in rows)
            {
                ListViewItem listitem = new ListViewItem();
                listitem.Tag = row["Stt"].ToString();
                listitem.Text = row["wsURL"].ToString();
                listitem.SubItems.Add(row["isEnable"].ToString() == "1" ? "Hoạt động" : "Ngừng họat động");
                listWeb.Items.Add(listitem);
            }
            foreach (DataRow row in rows)
            {
                TreeListNode par = treeList1.Nodes.Add(new object[] { row["wsURL"].ToString() });
                par.Tag = row["Stt"].ToString();
                DataRow[] srows = dtChiTieu.Select("webId = '" + row["Stt"].ToString() + "'");
                foreach (DataRow subrow in srows)
                {
                    string caption = "Từ ngày [" + ((DateTime)subrow["batdau"]).ToString("dd/MM/yyyy") + "] đến ngày [" + ((DateTime)subrow["ketthuc"]).ToString("dd/MM/yyyy") + "]";
                    TreeListNode node = par.Nodes.Add(new object[] { caption });
                    node.Tag = subrow["Stt"].ToString();
                }
            }
            treeList1.ExpandAll();
            repositoryItemLookUpEdit1.DataSource = dtWebsite;
            repositoryItemLookUpEdit1.DisplayMember = "wsURL";
            repositoryItemLookUpEdit1.ValueMember = "Stt";
        }
        void printVetinh(string value = "")
        {
            listBot.Items.Clear();
            DataRow[] dr = dtBots.Select(value);
            foreach (DataRow row in dr)
            {
                ListViewItem i = new ListViewItem();
                i.Text = row["tenmay"].ToString();
                i.Tag = row["Stt"].ToString();
                i.SubItems.Add(row["trangthai"].ToString() == "1" ? "Online" : "Offline");
                i.SubItems.Add(row["dsWebs"].ToString());
                listBot.Items.Add(i);
            }
        }
        void printLog(string value = "")
        {
            listLog.Items.Clear();
            DataRow[] dr = dtLogs.Select(value);
            foreach (DataRow row in dr)
            {
                ListViewItem i = new ListViewItem();
                i.Text = row["PageUrl"].ToString();
                i.Tag = row["Stt"].ToString();
                i.SubItems.Add(row["ipAddress"].ToString());
                i.SubItems.Add(row["batdau"].ToString());
                i.SubItems.Add(row["ketthuc"].ToString());
                i.SubItems.Add(row["luotxem"].ToString());
                i.SubItems.Add(row["tenmay"].ToString());
                listLog.Items.Add(i);
            }
        }
        void printLich(string value = "")
        {
            DataRow[] rows = dtSchedules.Select(value);
            schedulerStorage1.Appointments.Clear();
            schedulerControl1.ActiveViewType = SchedulerViewType.Month;
            schedulerControl1.Start = DateTime.Now;
            schedulerControl1.ActiveView.AppointmentDisplayOptions.StartTimeVisibility = AppointmentTimeVisibility.Never;
            schedulerControl1.ActiveView.AppointmentDisplayOptions.EndTimeVisibility = AppointmentTimeVisibility.Never;
            foreach (DataRow row in rows)
            {
                string luotxem = string.IsNullOrEmpty(row["luotxem"].ToString()) ? "0" : row["luotxem"].ToString();
                string luocxemhientai = string.IsNullOrEmpty(row["luocxemhientai"].ToString()) ? "0" : row["luocxemhientai"].ToString();
                DateTime a = (DateTime)row["ngay"];
                DateTime begin = new DateTime(a.Year, a.Month, a.Day, 0, 0, 0, 0);
                DateTime end = new DateTime(a.Year, a.Month, a.Day, 23, 59, 59, 0);
                int labelid = 0;
                string subject = "";
                string status = "";
                bool finish = false;
                if (int.Parse(luocxemhientai) < int.Parse(luotxem))
                {
                    subject = "Đã xem : " + luocxemhientai + "\nLượt xem chỉ tiêu : " + luotxem;
                    status = "đang chạy";
                    finish = false;
                }
                else
                {
                    subject = "Đã xem : " + luocxemhientai + "\nLượt xem chỉ tiêu : " + luotxem;
                    status = "hoàn tất";
                    finish = true;
                }
                if (a.Date == DateTime.Now.Date)
                {
                    labelid = 2;
                }
                else if (a.Date < DateTime.Now.Date)
                {
                    labelid = 1;
                    if (!finish) { status = "ngừng chạy"; labelid = 3; }
                }
                else
                {
                    labelid = 4;
                    if (!finish) status = "chưa chạy";
                }
                string des = row["wsUrl"].ToString();
                subject = subject + "( " + status + " )";
                AddSchedulerStorage(subject, begin, end, des, labelid);
            }

        }
        public void AddSchedulerStorage(string subject, DateTime dateStart, DateTime dateEnd, string des, int labelId)
        {
            Appointment apt = new Appointment();
            apt.Subject = subject;
            apt.Start = dateStart;
            apt.End = dateEnd;
            apt.LabelId = labelId;
            apt.Description = des;
            schedulerStorage1.Appointments.Add(apt);
        }
        void loadChiTieu(string webid)
        {
            listChitieu.Items.Clear();
            DataRow[] rows = dtChiTieu.Select("webId = '" + webid + "'");
            foreach (DataRow item in rows)
            {
                ListViewItem i = new ListViewItem();
                i.Text = item["luotxem"].ToString();
                i.Tag = item["Stt"].ToString();
                i.SubItems.Add(item["batdau"].ToString());
                i.SubItems.Add(item["ketthuc"].ToString());
                i.SubItems.Add(item["trangthai"].ToString() == "1" ? "Đang chạy" : "Đã ngưng");
                listChitieu.Items.Add(i);
            }
        }
        void loadPageURL(string webid)
        {
            listTrang.Items.Clear();
            DataRow[] rows = dtpageUrl.Select("webID = '" + webid + "'");
            foreach (DataRow item in rows)
            {
                ListViewItem i = new ListViewItem();
                i.Text = item["PageUrl"].ToString();
                i.Tag = item["Stt"].ToString();
                i.SubItems.Add(item["isEnable"].ToString() == "1" ? "Hoạt động" : "Ngừng họat động");
                listTrang.Items.Add(i);
            }
        }
        void loadwait()
        {
            this.Controls.Add(wait);
            wait.Appearance.BackColor = System.Drawing.Color.Transparent;
            wait.Appearance.Options.UseBackColor = true;
            wait.AppearanceCaption.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F);
            wait.AppearanceCaption.Options.UseFont = true;
            wait.AppearanceDescription.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F);
            wait.AppearanceDescription.Options.UseFont = true;
            wait.Location = new Point((this.Width / 2) - 174, (this.Height / 2) - 54);
            wait.Name = "Waiting";
            wait.Size = new System.Drawing.Size(174, 54);
            wait.Text = "Waiting";
            wait.Visible = true;
        }
        void doloadweb()
        {
            this.Enabled = false;
            BWWebsite.RunWorkerAsync();
        }

        private void BWWebsite_DoWork(object sender, DoWorkEventArgs e)
        {
            loadwebsite();
        }

        private void BWWebsite_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            printWebsite();
            this.Enabled = true;
        }

        private void listWeb_MouseClick(object sender, MouseEventArgs e)
        {
            ListViewItem item = listWeb.GetItemAt(e.X, e.Y);
            if (item != null)
            {
                loadChiTieu(item.Tag.ToString());
                loadPageURL(item.Tag.ToString());
            }
        }

        private void ctm_WebClick(object sender, EventArgs e)
        {
            ListView list;
            string caseNo = "0";
            dynamic obj = null;
            ToolStripMenuItem item = sender as ToolStripMenuItem;
            ContextMenuStrip a = item.Owner as ContextMenuStrip;
            list = a.SourceControl as ListView;
            caseNo = item.Tag.ToString();
            if (list == null) return;
            if (caseNo != "1" && list.SelectedItems.Count == 0) return;
            switch (caseNo)
            {
                case "1":
                    if (list.Name == listWeb.Name)
                    {
                        frm_themWeb frm = new frm_themWeb(dtCustomer);
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            doloadweb();
                        }
                    }
                    if (list.Name == listChitieu.Name)
                    {
                        frm_themchitieu frm = new frm_themchitieu(dtWebsite);
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            doloadweb();
                        }
                    }
                    if (list.Name == listTrang.Name)
                    {
                        frm_themPage frm = new frm_themPage(dtWebsite);
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            doloadweb();
                        }
                    }
                    break;
                case "2":
                    if (list.Name == listWeb.Name)
                    {
                        DataRow[] rows = dtWebsite.Select("Stt = '" + list.SelectedItems[0].Tag.ToString() + "'");
                        if (rows.Length > 0)
                        {
                            obj = new
                            {
                                Stt = rows[0]["Stt"],
                                wsUrl = rows[0]["wsUrl"],
                                isEnable = rows[0]["isEnable"],
                                customer_id = rows[0]["customer_id"]
                            };
                            frm_themWeb frm = new frm_themWeb(obj, dtCustomer);
                            if (frm.ShowDialog() == DialogResult.OK)
                            {
                                doloadweb();
                            }
                        }
                    }
                    if (list.Name == listChitieu.Name)
                    {
                        DataRow[] rows = dtChiTieu.Select("Stt = '" + list.SelectedItems[0].Tag.ToString() + "'");
                        if (rows.Length > 0)
                        {
                            obj = new
                            {
                                Stt = rows[0]["Stt"],
                                webId = rows[0]["webId"],
                                batdau = (DateTime)rows[0]["batdau"],
                                ketthuc = (DateTime)rows[0]["ketthuc"],
                                luotxem = rows[0]["luotxem"]
                            };
                            frm_themchitieu frm = new frm_themchitieu(obj, dtWebsite);
                            if (frm.ShowDialog() == DialogResult.OK)
                            {
                                doloadweb();
                            }
                        }
                    }
                    if (list.Name == listTrang.Name)
                    {
                        DataRow[] rows = dtpageUrl.Select("Stt = '" + list.SelectedItems[0].Tag.ToString() + "'");
                        if (rows.Length > 0)
                        {
                            obj = new
                            {
                                Stt = rows[0]["Stt"],
                                WebsiteID = rows[0]["webID"],
                                PageUrl = rows[0]["PageUrl"],
                                isEnable = rows[0]["isEnable"]
                            };
                            frm_themPage frm = new frm_themPage(obj, dtWebsite);
                            if (frm.ShowDialog() == DialogResult.OK)
                            {
                                doloadweb();
                            }
                        }
                    }
                    break;
                case "3":
                    string key = "";
                    string name = "";
                    if (list.Name == listWeb.Name) { key = "xoaWeb"; name = "Website"; }
                    if (list.Name == listChitieu.Name) { key = "xoaChitieu"; name = "Lịch trình"; }
                    if (list.Name == listTrang.Name) { key = "xoaPage"; name = "Trang"; }

                    DialogResult res = MessageBox.Show("Bạn có muốn xóa " + name + " đã chọn không?", "Xác nhận",
                                                                            MessageBoxButtons.YesNo,
                                                                            MessageBoxIcon.Question,
                                                                            MessageBoxDefaultButton.Button2);
                    if (res == DialogResult.Yes)
                    {
                        string id = list.SelectedItems[0].Tag.ToString();
                        string resu = Functions.getdata(wc, key, id);
                        if (resu == "1")
                        {
                            doloadweb();
                        }
                        else MessageBox.Show("Sự cố khi xóa !");
                    }
                    break;
            }
        }

        private void btLammoi_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            initDB();
            loadwebsite();
            printWebsite();
            loadDTLich();
            loadDTLog();
            loadDTVetinh();
            printVetinh();
            printLog();
            printLich();
            loadCustomer();
        }

        private void listChitieu_MouseClick(object sender, MouseEventArgs e)
        {
            ListViewItem item = listChitieu.GetItemAt(e.X, e.Y);
            item.Selected = true;
        }

        private void listTrang_MouseClick(object sender, MouseEventArgs e)
        {
            ListViewItem item = listTrang.GetItemAt(e.X, e.Y);
            item.Selected = true;
        }

        private void schedulerControl1_InitAppointmentImages(object sender, AppointmentImagesEventArgs e)
        {
            AppointmentImageInfo info = new AppointmentImageInfo();
            info.Image = Properties.Resources.x16Piechart;
            e.ImageInfoList.Add(info);
        }

        private void schedulerControl1_ActiveViewChanged(object sender, EventArgs e)
        {
            schedulerControl1.Start = DateTime.Now;
            schedulerControl1.ActiveView.AppointmentDisplayOptions.StartTimeVisibility = AppointmentTimeVisibility.Never;
            schedulerControl1.ActiveView.AppointmentDisplayOptions.EndTimeVisibility = AppointmentTimeVisibility.Never;
        }

        private void ctmi_editpage_Click(object sender, EventArgs e)
        {
            frm_danhsachpage frm = new frm_danhsachpage(dtWebsite, dtpageUrl, listBot.SelectedItems);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                loadDTVetinh();
                printVetinh();
            }
        }

        private void btSearchWeb_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            printWebsite("wsURL like '%" + txtSearch.EditValue.ToString() + "%'");
        }

        private void btLammoiStatus_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string resu = Functions.getdata(new WebClient(), "updateStatus", "");
            if (resu == "1")
            {
                loadDTVetinh();
                printVetinh();
            }
            else MessageBox.Show("Sự cố khi thao tác với CSDL");
        }

        private void btLocLich_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string ser = "ngay >= '" + (DateTime)date_lich_from.EditValue + "' AND ngay <= '" + (DateTime)date_lich_to.EditValue + "'";
            if (!string.IsNullOrEmpty(nodeseletcted)) ser = ser + "AND chitieuId = '" + nodeseletcted + "'";
            printLich(ser);
            schedulerControl1.Start = (DateTime)date_lich_from.EditValue;
        }
        string nodeseletcted;
        private void treeList1_MouseClick(object sender, MouseEventArgs e)
        {
            TreeListNode node = treeList1.CalcHitInfo(new Point(e.X, e.Y)).Node;
            if (node != null)
            {
                if (node.Level == 1)
                {
                    printLich("chitieuId = '" + node.Tag.ToString() + "'");
                    nodeseletcted = node.Tag.ToString();
                }
                if (node.Level == 0)
                {
                    if (node.HasChildren)
                    {
                        string res = "";
                        foreach (TreeListNode snode in node.Nodes)
                        {
                            res = res + snode.Tag.ToString() + ",";
                        }
                        if (res.Length > 0) res = res.Substring(0, res.Length - 1);
                        printLich("chitieuId in (" + res + ")");
                    }
                    else
                    {
                        printLich("chitieuId = 0");
                    }

                }
            }

        }

        private void btUpdateLich_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //var obj = new
            //{

            //};
            //string resu = Functions.getdata(new WebClient(), "updateLich", json);
        }

        private void btLocLogs_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string webid = search_log_website.EditValue == null ? null : search_log_website.EditValue.ToString();
            string from = date_log_fr.EditValue == null ? null : date_log_fr.EditValue.ToString();
            string to = date_log_to.EditValue == null ? null : date_log_to.EditValue.ToString();
            string select = "";
            if (webid != null) select = " WebsiteID = '" + webid + "'";
            if (from != null && to != null) select = " batdau >= '" + from + "' AND batdau <= '" + to + "'";
            if (webid != null && from != null && to != null) select = " WebsiteID = '" + webid + "' AND batdau >= '" + from + "' AND batdau <= '" + to + "'";
            printLog(select);
        }

    }
}